<template>
  <div
    class="write_container"
    :style="{ paddingTop: isMobile == 'true' ? '0px' : '50px' }"
  >
    <div class="top_container" v-if="isMobile == 'false'">
      <div class="back_arrow">
        <van-icon name="arrow-left" size="0.6rem" @click="backHandle()" />
      </div>
      <div class="top_title_container">
        <div class="title">{{ form.currentTitle }}</div>
      </div>
      <!-- <div class="search_container">
        <div class="search_item">
          <van-icon name="todo-list-o" size="0.6rem" />
          <van-icon name="more-o" size="0.6rem" style="margin-left: 0.6rem" />
        </div>
      </div> -->
    </div>
    <!-- <div class="tip">所写内容会实时保存</div> -->
    <div class="field_container">
      <div class="form_container">
        <div class="form_item" v-for="(item, index) in fieldList" :key="index">
          <div class="base_label">
            <div class="star" v-if="item.state">*</div>
            <div class="label">{{ item.key }}</div>
          </div>
          <div class="input_container">
            <!-- 文本框 -->
            <van-field
              v-model="item.content"
              autosize
              type="textarea"
              :placeholder="item.promptText ? item.promptText : '请输入'"
              show-word-limit
              :maxlength="form.maxWord"
              @blur="judgeBadWord(item.content, index)"
              v-if="item.type == 1"
            />
            <!-- 数字 -->
            <van-field
              v-model="item.content"
              type="number"
              autosize
              placeholder="请输入"
              show-word-limit
              v-if="item.type == 2"
            />

            <!-- 日期 -->
            <van-cell
              title="选择日期"
              is-link
              :value="item.content"
              @click="dateHandle(index)"
              v-if="item.type == 5"
            />

            <!-- 单选框 -->
            <div
              class="select_li"
              v-if="item.type == 3"
              @click="radioSelect(item, index)"
            >
              <div class="li_select">{{ item.content || "请选择" }}</div>
              <van-icon
                name="arrow-down"
                size="0.4rem"
                style="font-weight: bold"
                color="#0087fd"
              />
            </div>

            <!-- 多选框 -->
            <div
              class="select_li"
              v-if="item.type == 7"
              @click="multiSelect(item, index)"
            >
              <div class="li_select">{{ item.content || "请选择" }}</div>
              <van-icon
                name="arrow-down"
                size="0.4rem"
                style="font-weight: bold"
                color="#0087fd"
              />
            </div>

            <!-- 上传图片 -->
            <div class="img_container" v-if="item.type == 8">
              <uploadImg
                @updateFileList="updateImgList"
                :fileList="item.content || []"
              />
            </div>

            <!-- 上传文件 -->
            <div class="file_container" v-if="item.type == 9">
              <uploadImg
                fileType=".pdf,.doc,.docx"
                @updateFileList="updateFile"
                :fileList="item.content || []"
                maxSize="1100000000"
              />
            </div>
          </div>
        </div>
      </div>
      <div class="setting_container">
        <div class="setting_item">
          <div class="send_person">
            <div class="base_label">
              <div class="label">发送到人</div>
            </div>
            <van-icon
              name="add-o"
              size="0.5rem"
              style="font-weight: bold; cursor: pointer"
              color="#0087fd"
              @click="sendOpen()"
            />
          </div>
          <div class="send_list">
            <div class="person_li" v-for="item in sendTo" :key="item.userId">
              <div class="avatar">
                <img :src="item.img" alt="" />
                <div class="lock">
                  <van-icon
                    class="iconfont"
                    class-prefix="icon"
                    name="suozhu1"
                    size="0.3rem"
                    color="#fff"
                    style="font-weight: bold"
                  />
                </div>
              </div>
              <div class="name">{{ item.userName }}</div>
            </div>
            <div
              class="person_li add_send"
              v-for="item in addSendList"
              :key="item.userId"
              @click="sendOpen()"
            >
              <div class="avatar">
                <img :src="item.img" alt="" />
              </div>
              <div class="name">{{ item.userName }}</div>
            </div>
          </div>
        </div>
        <div class="setting_item trans">
          <div class="base_label">
            <div class="label">仅接收人可见，不可转发</div>
          </div>
          <van-switch v-model="isForward" size="20px" />
        </div>
        <div class="tips">除了你自己，任何人不可转发你的日志内容</div>
        <div class="setting_item trans" style="display: block">
          <div class="base_label" style="justify-content: space-between">
            <div class="label">定时发送</div>
            <van-switch
              v-model="timeSendFlag"
              size="20px"
              @change="timeHandle"
            />
          </div>
          <div class="time" v-if="timeSendFlag">
            <van-cell
              title="请选择"
              is-link
              :value="taskTime"
              @click="timeFlag = true"
            />
          </div>
        </div>
      </div>
    </div>

    <div class="bottom_container">
      <div class="tab_item">
        <div class="btn" @click="submit()" v-if="detailId">编辑日志</div>
        <div class="btn" @click="submit()" v-else>提交日志</div>
      </div>
    </div>

    <!-- 单选弹框 -->
    <van-popup
      v-model:show="radioFlag"
      position="center"
      round
      :style="{ width: '60%' }"
      @close="closeRadio()"
    >
      <div class="select_pop">
        <van-radio-group v-model="radioValue">
          <van-radio
            v-for="(item, index) in radioData"
            :key="index"
            :name="item"
            >{{ item }}</van-radio
          >
        </van-radio-group>
      </div>
    </van-popup>

    <!-- 多选弹框 -->
    <van-popup
      v-model:show="multiFlag"
      position="center"
      round
      :style="{ width: '50%', height: '40%' }"
      @close="closeMulti()"
    >
      <div class="select_pop">
        <van-checkbox-group v-model="multiValue" ref="checkboxGroup">
          <van-checkbox
            shape="square"
            v-for="(item, index) in multiData"
            :key="index"
            :name="item"
            >{{ item }}</van-checkbox
          >
        </van-checkbox-group>
      </div>
    </van-popup>

    <!-- 日期 -->
    <van-calendar
      v-model:show="dateFlag"
      :min-date="minDate"
      @confirm="onConfirm"
    />

    <!-- 发送人弹窗 -->
    <VanDialog
      v-model:show="defaultFlag"
      :closeOnClickOverlay="false"
      :showConfirmButton="false"
      title="深圳市斯贝达电子有限公司"
    >
      <SelectUser @submitUser="setDefaultForUser" :list="addSendList" />
    </VanDialog>

    <!-- 定时发送 -->
    <VanDialog
      v-model:show="timeFlag"
      :closeOnClickOverlay="false"
      :showConfirmButton="false"
    >
      <van-datetime-picker
        v-model="currentDate"
        :min-date="minTime"
        type="datetime"
        title="选择完整时间"
        @cancel="cancelTime"
        @confirm="confirmTime"
      />
    </VanDialog>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  GetTemplateInfo,
  AddLogRecord,
  GetLogRecord,
  UpdateLogRecord,
} from "@/api/log";
import SelectUser from "@/components/selectUser.vue";
import { getSimpleDate } from "@/utils/days";
import { Toast } from "vant";
import { Local } from "@/utils/storage";
import uploadImg from "@/components/uploadImg.vue";

onMounted(() => {
  nextTick(() => {
    isMobile.value = localStorage.getItem("isMobile");
  });
  form.value.userId = Local.get("userId");
  form.value.userName = Local.get("userName");
  form.value.img = Local.get("userImg");
  if (route.query.templateId) {
    templateId.value = route.query.templateId;
    getTemplateInfo();
  }
  if (route.query.detailId) {
    detailId.value = route.query.detailId;
    getLogInfo();
  }
});
const router = useRouter();
const route = useRoute();
const backHandle = () => {
  router.go(-1);
};
const isMobile = ref(false);
const templateId = ref(null);
const detailId = ref(null);
const form = ref({
  templateId: "",
  userId: "",
  userName: "",
  img: "",
  currentTitle: "",
  maxWord: "",
  minWord: "",
});
const tabList = ref([
  {
    label: "看日志",
    icon: "newspaper-o",
  },
  {
    label: "统计",
    icon: "bar-chart-o",
  },
]);
const fieldList = ref([]);
const sendTo = ref([]);
const addSendList = ref([]);
const getTemplateInfo = async () => {
  const res = await GetTemplateInfo({ id: templateId.value });
  if (res.code == 200) {
    form.value.currentTitle = res.data.name;
    form.value.maxWord = res.data.maxWord ? res.data.maxWord : null;
    form.value.minWord = res.data.minWord;
    form.value.templateId = res.data.id;
    fieldList.value = res.data.fields;
    sendTo.value = res.data.defaultFor;
    fieldList.value.forEach((item) => {
      item.value = item.value.split(",");
      if (item.type == 8 || item.type == 9) {
        item["content"] = [];
      } else {
        item["content"] = "";
      }
    });
  }
};
//编辑回显
const getLogInfo = async () => {
  const res = await GetLogRecord({ id: detailId.value });
  if (res.code == 200) {
    form.value.currentTitle = res.data.templateName;
    form.value.templateId = res.data.id;
    form.value.maxWord = res.data.maxWord ? res.data.maxWord : null;
    form.value.minWord = res.data.minWord;
    fieldList.value = res.data.fields;
    sendTo.value = res.data.sendTo.filter((item) => {
      return item.lock == true;
    });
    addSendList.value = res.data.sendTo.filter((item) => {
      return item.lock == false;
    });
    fieldList.value.forEach((item) => {
      item.value = JSON.parse(item.value);
      item.content = JSON.parse(item.content);
    });
    if (res.data.taskTime) {
      timeSendFlag.value = true;
      taskTime.value = res.data.taskTime;
    }
  }
};
const isForward = ref(false);

//敏感词过滤
const judgeBadWord = (str, i) => {
  const badWord = [
    { sensitiveWord: "打架", replaceWord: "A" },
    { sensitiveWord: "研究所", replaceWord: "B" },
  ];
  const newArr = [];
  badWord.forEach((item) => {
    newArr.push({
      sensitiveWord: item.sensitiveWord,
      replaceWord: item.replaceWord,
    });
  });
  // trim() 方法不会改变原始字符串 去掉首尾空白符
  let contents = "";
  contents = str.trim();
  newArr.forEach((item) => {
    if (contents.indexOf(item.sensitiveWord) != -1) {
      const reg = new RegExp(item.sensitiveWord, "gi");
      contents = contents.replace(reg, item.replaceWord);
    }
  });
  fieldList.value[i].content = contents;
};

//单选
const radioValue = ref("");
const currentIndex = ref(-1);
const radioFlag = ref(false);
const radioData = ref([]);
const radioSelect = (item, index) => {
  currentIndex.value = index;
  radioValue.value = item.content;
  radioFlag.value = true;
  radioData.value = item.value;
};
const closeRadio = () => {
  fieldList.value[currentIndex.value].content = radioValue;
};
//多选
const multiValue = ref([]);
const multiFlag = ref(false);
const multiData = ref([]);
const multiSelect = (item, index) => {
  currentIndex.value = index;
  multiValue.value = item.content ? item.content : [];
  multiFlag.value = true;
  multiData.value = item.value;
};
const closeMulti = () => {
  fieldList.value[currentIndex.value].content = JSON.parse(
    JSON.stringify(multiValue.value)
  ).length
    ? multiValue.value
    : null;
};
//日期
const dateFlag = ref(false);
const dateHandle = (index) => {
  dateFlag.value = true;
  currentIndex.value = index;
};
const minDate = new Date(2010, 0, 1);
const formatDate = (date) =>
  `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
const onConfirm = (value) => {
  dateFlag.value = false;
  fieldList.value[currentIndex.value].content = formatDate(value);
};

// 上传图片
const updateImgList = (row) => {
  console.log("上传图片", row);
};

// 上传附件
const updateFile = (row) => {
  console.log("上传文件", row);
};

//发送人
const defaultFlag = ref(false);
const sendOpen = () => {
  defaultFlag.value = true;
};
const setDefaultForUser = (val) => {
  let arrs = val.map((item) => {
    return {
      userId: item.id,
      userName: item.label,
      img: item.img,
      lock: false,
    };
  });
  let arrList = JSON.parse(JSON.stringify(sendTo.value));
  for (let i = 0; i < arrList.length; i++) {
    for (let j = 0; j < arrs.length; j++) {
      if (arrList[i].userId == arrs[j].userId) {
        arrs.splice(j, 1);
      }
    }
  }
  addSendList.value = arrs;
  defaultFlag.value = false;
};
//定时发送
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes() + 15;
const currentDate = ref(new Date(year, month, day, hour, minute));
const minTime = ref(new Date(year, month, day, hour, minute));
const timeSendFlag = ref(false);
const timeFlag = ref(false);
const taskTime = ref("");
const timeHandle = (e) => {
  if (e) {
    timeSendFlag.value = true;
  } else {
    timeSendFlag.value = false;
    taskTime.value = "";
  }
};
const cancelTime = () => {
  timeFlag.value = false;
};
const confirmTime = () => {
  taskTime.value = getSimpleDate(currentDate.value);
  timeFlag.value = false;
};
let submitFlag = ref(true);
//提交日志
const submit = async () => {
  if (submitFlag.value) {
    let sendList = [
      ...JSON.parse(JSON.stringify(sendTo.value)),
      ...JSON.parse(JSON.stringify(addSendList.value)),
    ];
    console.log("fieldList", fieldList.value);
    for (let i = 0; i < fieldList.value.length; i++) {
      if (fieldList.value[i].state && !fieldList.value[i].content) {
        return Toast.fail("必填项不能为空");
      }
      if (
        fieldList.value[i].type == 1 &&
        fieldList.value[i].state == 1 &&
        fieldList.value[i].content.length < form.value.minWord
      ) {
        return Toast.fail(`输入框字数不能少于${form.value.minWord}`);
      }
    }
    let fields = fieldList.value.map((item) => {
      return {
        key: item.key,
        sort: item.sort,
        type: item.type,
        content: JSON.stringify(item.content),
        value: JSON.stringify(item.value),
        promptText: item.promptText,
        state: item.state,
      };
    });
    console.log("fields", fields);
    submitFlag.value = false;
    let req = {
      templateId: form.value.templateId,
      sendTo: sendList,
      userId: form.value.userId,
      userName: form.value.userName,
      img: form.value.img,
      isForward: isForward.value,
      taskTime: taskTime.value ? taskTime.value : null,
      fields: fields,
    };
    if (detailId.value) {
      //编辑
      let editReq = { ...req, id: detailId.value };
      const res = await UpdateLogRecord(editReq);
      if (res.code == 200) {
        Toast.success("编辑成功");
        localStorage.setItem("logTab", 0);
        if (JSON.parse(JSON.stringify(taskTime.value))) {
          localStorage.setItem("readLogTab", "3");
        } else {
          localStorage.setItem("readLogTab", "1");
        }
        setTimeout(() => {
          submitFlag.value = true;
          router.push({ name: "log" });
        }, 1000);
      } else {
        submitFlag.value = true;
      }
    } else {
      //新增
      const res = await AddLogRecord(req);
      if (res.code == 200) {
        Toast.success("提交成功");
        localStorage.setItem("logTab", 0); //回到看日志页面
        if (JSON.parse(JSON.stringify(taskTime.value))) {
          localStorage.setItem("readLogTab", "3"); //有定时任务就到定时发送列表
        } else {
          localStorage.setItem("readLogTab", "1"); //没有就到已发送列表
        }
        setTimeout(() => {
          submitFlag.value = true;
          router.push({ name: "log" });
        }, 1000);
      } else {
        submitFlag.value = true;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.write_container {
  width: 100%;
  height: 100vh;
  font-family: 黑体;
  padding-bottom: 70px;
  box-sizing: border-box;
  position: relative;
  .top_container {
    width: 100%;
    height: 50px;
    position: absolute;
    top: 0;
    left: 0;
    display: flex;
    align-items: center;
    padding: 0 0.5rem;
    box-sizing: border-box;
    background-color: #fff;
    .back_arrow {
      height: 100%;
      display: flex;
      align-items: center;
      cursor: pointer;
    }
    .top_title_container {
      flex: 1;
      .title {
        font-size: 0.5rem;
        font-weight: bold;
        text-align: center;
      }
      .company {
        font-size: 0.3rem;
        color: #b0b0b0;
        text-align: center;
      }
    }
    .search_container {
      display: flex;
      align-items: center;
      .search_item {
        display: flex;
        align-items: center;
        font-size: 0.5rem;
      }
    }
  }
  .tip {
    width: 100%;
    padding: 6px;
    box-sizing: border-box;
    font-size: 0.4rem;
    color: #b2b2b2;
    text-align: right;
  }
  .field_container {
    width: 100%;
    height: 100%;
    overflow-y: scroll;
  }
  .base_label {
    font-size: 0.4rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    position: relative;
    .star {
      position: absolute;
      left: 0;
      color: red;
      font-weight: normal;
    }
    .label {
      margin-left: 10px;
    }
  }

  .form_container {
    border-bottom: 1px solid #ddd;
    .form_item {
      width: 100%;
      padding: 20px 10px;
      box-sizing: border-box;
      background-color: #fff;
      margin-top: 2px;

      .input_container {
        width: 100%;
        :deep(.van-cell) {
          padding-left: 10px;
          box-sizing: border-box;
        }
        .select_li {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 0.3rem;
          margin: 10px;
          .li_select {
            font-size: 0.4rem;
          }
        }
        .img_container {
          margin: 10px;
          display: flex;
          align-items: center;
          .pic_list {
            width: 2rem;
            height: 2rem;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-wrap: wrap;
            position: relative;
            padding: 0;
            .del {
              width: 0.4rem;
              height: 0.4rem;
              position: absolute;
              top: 0px;
              right: 0px;
              background-color: #0087fd;
              display: flex;
              justify-content: center;
              align-items: center;
              border-radius: 50%;
              cursor: pointer;
            }
            img {
              width: 90%;
              height: auto;
            }
          }
        }
        .file_container {
          margin: 10px;
          .file_list {
            .file {
              display: flex;
              align-items: center;
              a {
                width: 5rem;
                font-size: 0.5rem;
                white-space: nowrap; /* 文本不换行 */
                overflow: hidden; /* 隐藏超出容器的内容 */
                text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
              }
              .del {
                display: flex;
                align-items: center;
                margin-left: 20px;
                cursor: pointer;
              }
            }
          }
          .van-uploader__input {
            display: none;
          }
        }
      }
    }
  }
  .setting_container {
    .setting_item {
      width: 100%;
      margin: 20px 0;
      background-color: #fff;
      padding: 20px;
      padding-left: 10px;
      box-sizing: border-box;
      .time {
        font-size: 0.4rem;
        margin-top: 10px;
        font-weight: normal;
        :deep(.van-cell) {
          padding-left: 10px;
          box-sizing: border-box;
        }
      }
    }
    .address {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .send_person {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .send_list {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      margin-left: 10px;
      margin-top: 20px;
      .person_li {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin: 5px;
        .avatar {
          width: 30px;
          height: 30px;
          position: relative;
          img {
            width: 100%;
            height: 100%;
            border-radius: 5px;
            border: 1px solid #ddd;
            position: absolute;
          }
          .lock {
            position: absolute;
            right: -5px;
            bottom: -5px;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: #0087fd;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }

        .name {
          width: 100%;
          text-align: center;
          font-size: 0.4rem;
          text-align: center;
          margin-top: 3px;
        }
      }
      .add_send {
        cursor: pointer;
      }
    }
    .trans {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .tips {
      color: #b4b4b4;
      font-size: 0.35rem;
      margin-left: 15px;
    }
  }
  .bottom_container {
    width: 100%;
    height: 60px;
    display: flex;
    justify-content: space-around;
    align-items: center;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    border-top: 1px solid #ddd;
    .tab_item {
      width: 90%;
      font-size: 0.3rem;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      .btn {
        width: 100%;
        height: 40px;
        background-color: #0087fd;
        border-radius: 5px;
        font-size: 0.5rem;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #fff;
      }
    }
  }
  .select_pop {
    width: 100%;
    height: 100%;
    display: flex;
    padding: 20px;
    box-sizing: border-box;
    .van-radio-group {
      font-size: 0.4rem;
      .van-radio {
        margin: 10px 0;
      }
    }
    .van-checkbox {
      font-size: 0.4rem;
      margin: 10px 0;
    }
  }
}
</style>
